package com.feige.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feige.constant.Constants;
import com.feige.pojo.DataFile;
import com.feige.service.DataFileService;
import com.feige.result.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 资料 前端控制器
 * </p>
 *
 * @author feige
 * @since 2021-03-08
 */
@Api(tags = "资料控制器")
@RestController
@RequestMapping("/courseware/data-file")
public class DataFileController {

    @Resource
    private DataFileService dataFileService;


    @GetMapping("/{courseId}/{pageNum}")
    public AjaxResult get(@PathVariable String courseId, @PathVariable Integer pageNum){
        Page<DataFile> page = new Page<>(pageNum, Constants.PAGE_SIZE * 2);
        QueryWrapper<DataFile> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId).orderByDesc("gmt_create");
        dataFileService.page(page,wrapper);
        AjaxResult success = AjaxResult.success(page.getRecords());
        success.put("total",page.getTotal());
        return success;
    }

    @PostMapping("/save")
    public AjaxResult save(MultipartFile file, DataFile dataFile) throws IOException {
        return dataFileService.uploadAndSave(file,dataFile);
    }

    @GetMapping("/get/{id}")
    public AjaxResult getDataFileById(@PathVariable Integer id){
        DataFile dataFile = dataFileService.getById(id);
        if (ObjectUtil.isNotEmpty(dataFile)){
            return AjaxResult.success(dataFile);
        }else {
            return AjaxResult.error(5005,"未查询到数据！");
        }
    }

}

